package com.hcmu.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import vanhoc.android.utils.AlertDialogManager;

import com.hcmu.R;
import com.hcmu.dto.DatabaseHelper;
import com.hcmu.dto.MainMenuDTO;
import com.hcmu.dto.CategoryDTO;
import com.hcmu.model.MainHomeModel;
import com.hcmu.view.MainHome.CreateNewStory;
import com.hcmu.view.MainHome.FavouriteList;
import com.hcmu.view.MainHome.OfflineMainView;
import com.hcmu.view.MainHome.ViewStoryDetailOffline;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MenuFragment extends ListFragment {
	MainHomeModel mainModel;
	List<CategoryDTO> typeList;
	Dialog optionDialog;
	Dialog dialogEdit;
	DatabaseHelper dbHelper;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		View header = LayoutInflater.from(getActivity()).inflate(R.layout.main_menu_item3, null);
		this.getListView().addHeaderView(header);
		
		TextView txtFavourite = (TextView) header.findViewById(R.id.txtFavourite);
		txtFavourite.setText(getResources().getString(R.string.FAVOURITES));
		txtFavourite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getActivity(), FavouriteList.class));
				((MenuActivity)getActivity()).getSlideoutHelper().close();
			}
		});
		
		dbHelper = new DatabaseHelper(getActivity());
		
		//init database object
		mainModel = new MainHomeModel(getActivity());
		
		//init menu
		initMenuListView();
	}
	
	
	
	private void initMenuListView() {
		typeList = mainModel.getStoryType();
		 ArrayList<MainMenuDTO> list = new ArrayList<MainMenuDTO>();
	        for (int i = 0; i < typeList.size(); i++) {
	        	list.add(new MainMenuDTO(BitmapFactory.decodeResource(getResources(), 
	        				R.drawable.ic_menu_quantam), typeList.get(i).getTitle()));
			}

			setListAdapter(new Funstory_MainMenu_Addapter(getActivity(),list));
			getListView().setCacheColorHint(R.color.TRANSPARENT);
			getListView().setDividerHeight(0);
			getListView().setBackgroundResource(R.color.BACK_GROUND_MENU_COLOR);
			getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View v,
						int position, long id) {
					
					int typeId = typeList.get(position-1).getId();
					String typeTitle = typeList.get(position-1).getTitle();
					alertOptionListDialog(typeId, typeTitle);
					
					return false;
				}
			});
	};
	

	
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		((MenuActivity)getActivity()).getSlideoutHelper().close();
		Intent it = new Intent(getActivity(), OfflineMainView.class);
		it.putExtra("CURRENT_TAB", position-1);
		startActivity(it);
	}

	
	
	protected void alertOptionListDialog(final int type_id, final String type_title) {
		optionDialog = new Dialog(getActivity(), 0);
		optionDialog.setTitle(type_title);
		optionDialog.setContentView(R.layout.listview);
		optionDialog.show();
		
		final String[] optionlist = getResources().getStringArray(R.array.simple_type_options);
		ListView lv = (ListView) optionDialog.findViewById(R.id.listView);
		
		ArrayAdapter<String>  adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, optionlist);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				switch (position) {
					case 0: //edit
						optionDialog.dismiss();
						editTypeTitle(type_id, type_title);
						break;
					case 1: //delete
						optionDialog.dismiss();
						deleteTypeStory(type_id);
						break;
					default:
						break;
				}
			}
		});
	}
	
	
	protected void deleteTypeStory(final int catid) {
		AlertDialog alert = new AlertDialog.Builder(getActivity()).create();
		alert.setTitle(getResources().getString(R.string.WARMNING_DELETE_TYPE));
		// Setting OK Button
		alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	dbHelper.openToWrite();
                	//delete type 
                	dbHelper.deleteCategory(catid);
                	
                	//delete the stories of the type
                	dbHelper.deleteStoryByCategory(catid);
                	dbHelper.close();
                	
                	initMenuListView();
                }
        });
		
		alert.setButton2("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		alert.show();
	}

	
	
	public void editTypeTitle(final int catId, String oldTitle){
		dialogEdit = new Dialog(getActivity(), 0);
		dialogEdit.setTitle(getResources().getString(R.string.EDIT));
		dialogEdit.setContentView(R.layout.layout_add_edit_title);
		dialogEdit.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		dialogEdit.show();
		
		//lay ve cac thanh phan cua layout add_playlist_layout thogn qua dialogAddPlaylist
		final EditText txtPlaylistTitle 	= (EditText) dialogEdit.findViewById(R.id.txtTitle);
		txtPlaylistTitle.setText(oldTitle);
		
		final Button btnSave 				= (Button) dialogEdit.findViewById(R.id.btnSave);
		Button btnCancel 					= (Button) dialogEdit.findViewById(R.id.btnCancel);
		
		//set onclickListener for btnSave
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String newTypeTitle = txtPlaylistTitle.getText().toString();
				
				if (newTypeTitle.equals(null) || newTypeTitle.equals("")) 
					AlertDialogManager.showAlertDialog(getActivity(), "Error", "Please enter title", false);
				else{
					//kiem tra xem title cua type nhap vao da ton tai hay chua.neu chua moi cho tao
					if (checkPlaylistTitle(newTypeTitle)) // neu co roi
						AlertDialogManager.showAlertDialog(getActivity(), "Error", "This title is exist.", false);
					else{
						dbHelper.openToWrite();
						dbHelper.updateCategory(catId, newTypeTitle);
						dbHelper.close();
						
						initMenuListView();
						dialogEdit.dismiss();
					}
				}
			}
		});
		
		/*set onclickListener for btnSave*/
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialogEdit.dismiss();
			}
		});
	}
	
	
	
	public Boolean checkPlaylistTitle(String pTitle){
		for (int i = 0; i < typeList.size(); i++) {
			if (typeList.get(i).getTitle().equals(pTitle)) {
				return true;
			}
		}
		return false;
	}
	
	
	
	
	/**
	 * 
	 * @author SEVEN
	 *
	 */
    public class Funstory_MainMenu_Addapter extends BaseAdapter  {
        private LayoutInflater mInflater;
        private ArrayList<MainMenuDTO> list;
        class ViewHolder {
           public TextView txt_Name;
           public ImageView img_Avatar;
           public EditText txt_Search;
           public ImageButton btn_Search;
           public void reset(){
        	   txt_Name = null;
        	   img_Avatar = null;
        	   txt_Search = null;
        	   btn_Search = null;
           }
        }

        public Funstory_MainMenu_Addapter(Context context) {
        	super();
            mInflater = LayoutInflater.from(context);                  

        }
        public Funstory_MainMenu_Addapter(Context context,ArrayList<MainMenuDTO> list) {
            mInflater = LayoutInflater.from(context);                  
            this.list = list;
        }
        
        public int getCount() {
            return list.size();
        }

        public long getItemId(int position) {
            return position;
        }

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder =null;
            MainMenuDTO dto = list.get(position);
            
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.main_menu_item1, null);
                holder = new ViewHolder();
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txt_Name = (TextView) convertView.findViewById(R.id.txt_main_menu_text);
            holder.img_Avatar =(ImageView) convertView.findViewById(R.id.img_text);

            LinearLayout l1 = (LinearLayout)convertView.findViewById(R.id.ln_img_text);
            LinearLayout l2 = (LinearLayout)convertView.findViewById(R.id.ln_text);
            l1.setVisibility(View.VISIBLE);
            l2.setVisibility(View.GONE);

            convertView.setBackgroundResource(R.drawable.menu_list_row);

            if(holder.txt_Name != null) holder.txt_Name.setText(dto.getText());
            if(holder.img_Avatar != null) holder.img_Avatar.setImageBitmap(dto.getImg());
            return convertView;
		}

        
    }
}
